const log4js = require('koa-log4');
const logger = log4js.getLogger('services::city');
const bson = require('bson');
const DBRef = bson.DBRef;
const helper = require('mongoskin').helper;
const db = require('../mongodb');


const findAll = async () => {
    return new Promise((resolve, reject) => {
        db.city.find().toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const findById = async (id) => {
    return new Promise((resolve, reject) => {
        db.city.findOne({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};


const findByPinyin = async (pinyin) => {
    return new Promise((resolve, reject) => {
        db.city.findOne({pinyin: pinyin}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const insert = async (city) => {
    city.createdAt = new Date();
    return new Promise((resolve, reject) => {
        db.city.insert(city, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};


const save = async (city) => {
    city.lastModifiedAt = new Date();
    return new Promise((resolve, reject) => {
        db.city.save(city, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const delById = async (id) => {
    return new Promise(function (resolve, reject) {
        db.city.remove({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

exports = module.exports = {
    findAll, findById, insert, save, delById, findByPinyin
};